package com.eight.cloud.security.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eight.cloud.core.global.model.LoginUser;
import com.eight.cloud.redisson.utils.TokenManager;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.eight.cloud.core.global.model.SysRole;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限拦截器
 *
 * @ClassName: AuthorityFilter
 * @Author: TXC
 * @Date: 2024-10-30 21:50
 **/
@AutoConfiguration
public class AuthorityFilter extends OncePerRequestFilter {
    @Resource
    private TokenManager tokenManager;

    /**
     * 权限操作
     *
     * @param request  请求
     * @param response 响应
     * @param chain    过滤器链
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取表单提供的数据
        LoginUser loginUser = tokenManager.getLoginUser(request);
        if (ObjectUtil.isNotNull(loginUser)) {
            List<String> roles = loginUser.getRoles().stream().map(SysRole::getCode).collect(Collectors.toList());
            if (ObjectUtil.isNull(roles)) {
                chain.doFilter(request, response);
                return;
            }
            Collection<GrantedAuthority> authorities =
                    roles.stream().filter(StrUtil::isNotBlank).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser.getUsername(), tokenManager.getAccessToken(request), authorities);
            authenticationToken.setDetails(loginUser);
            // 权限信息设置到权限上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        // 生成信息对象
        chain.doFilter(request, response);
    }
}
